﻿using JX.Core;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace JX.Dapper
{
	/// <summary>
	/// 工作单元实现类，基于Dapper
	/// </summary>
	public class UnitOfWork : IUnitOfWork
	{
		private readonly IContext _context;
		/// <summary>
		/// 构造注入器。
		/// 1、接受数据库上下文并赋值给内部属性。
		/// 2、开启事务。
		/// </summary>
		/// <param name="context">数据库上下文</param>
		public UnitOfWork(IContext context)
		{
			_context = context;
			_context.BeginTransaction();
		}

		/// <summary>
		/// 提交事务
		/// </summary>
		/// <returns></returns>
		public bool Commit()
		{
			if (!_context.IsTransactionStarted)
				throw new InvalidOperationException("Transaction have already been commited or disposed.");

			_context.Commit();
			return true;
		}
		/// <summary>
		/// 提交事务
		/// </summary>
		/// <returns></returns>
		public async Task<bool> CommitAsync()
		{
			if (!_context.IsTransactionStarted)
				throw new InvalidOperationException("Transaction have already been commited or disposed.");

			await Task.Run(() => _context.Commit());
			return true;
		}

		/// <summary>
		/// 销毁对象。如果启动了事务，则回滚事务。
		/// </summary>
		public void Dispose()
		{
			if (_context.IsTransactionStarted)
				_context.Rollback();
		}
		
	}
}
